
const MongoClient = require('mongodb').MongoClient
const util = require('./util')
const config = require('./config')

const logger = util.getLogger('db_helper')

let conn

module.exports = {
  async connect () {
    if (module.exports.idConnected) 
      return
    try{
      conn = await MongoClient.connect(config.mongo.url)
      module.exports.idConnected = true   //数据连接状态
      let db = conn.db()
      module.exports.db = db
      module.exports.jobs = db.collection('jobs')
      module.exports.logs = db.collection('logs')
      module.exports.test = db.collection('test')
      logger.info('连接 mongodb 成功')
    }catch(e){
      logger.error('连接 mongodb 异常：', e)
      module.exports.idConnected = false   //数据连接状态
      conn && conn.close()
      throw e;
    }
  }
}
